package com.tianruan.dc.common.store;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import java.util.Date;

/**
 *
 * @PS 自动续签token
 *
 */
@Slf4j
public class AutoRenewalRedisTokenStore  extends RedisTokenStore {

    @Value("${oauth.config.accessToken-validitySeconds}")
    private Integer accessTokenValiditySeconds;
    @Value("${oauth.config.refreshToken-validitySeconds}")
    private Integer refreshTokenValiditySeconds;

    public AutoRenewalRedisTokenStore(RedisConnectionFactory connectionFactory) {
        super(connectionFactory);
    }

    @Override
    public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
        log.debug("token续签开始");
        OAuth2Authentication result = this.readAuthentication(token.getValue());
        log.debug(JSON.toJSONString(result));
        if (result != null) {
            //如果token失效更新token时间
            DefaultOAuth2AccessToken oAuth2AccessToken = (DefaultOAuth2AccessToken) token;
            int expiresIn = oAuth2AccessToken.getExpiresIn();
            log.debug("token将在{}秒后过期", expiresIn);

            if (expiresIn < accessTokenValiditySeconds) {
                oAuth2AccessToken.setExpiration(new Date(System.currentTimeMillis() + (accessTokenValiditySeconds * 1000L)));
            }
            //将重新设置过的token过期时间设置到redis 此时会覆盖原本的过期时间
            storeAccessToken(token, result);

            log.debug("token过期已续期");
        }
        return result;
    }

}